package com.joint.web.action.finance;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.Duty;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.finance.CalculationYear;
import com.joint.core.service.CalculationYearService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/6.
 */
@ParentPackage("finance")
public class AjaxCalculationyearAction extends BaseFlowAction {
    @Resource
    private CalculationYearService calculationYearService;

    private CalculationYear calculationYear;
    private Users loginUser;
    private String viewtype;
    private int ifCentralStaff;
    private int numStatus;
    private String budgetfileId;
    private String finalAccountsfileId;
    private String budgetIds;
    private String finalAccountsIds;
    private String cname;

    public String execute(){
        return "calculationyear";
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state", BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                params.put("invalid", false);
                pager=calculationYearService.findByPagerAndLimit(false, "calculationyear", pager, params);
            }else if(viewtype.equals("2")){
                //已通过
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                params.put("invalid", false);
                pager=calculationYearService.findByPagerAndFinish( "calculationyear", pager, params);
            }else if(viewtype.equals("3")){
                //已失效
                params.put("invalid", true);
                pager=calculationYearService.findByPagerAndLimit(true, "calculationyear", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=calculationYearService.findByPagerAndLimit(true, "calculationyear", pager, params);
        }
        List<CalculationYear> cYearList;
        if (pager.getTotalCount() > 0){
            cYearList = (List<CalculationYear>) pager.getList();
        }else{
            cYearList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(CalculationYear c:cYearList){
            String state=c.getProcessState().name();
            rMap = new HashMap<String,Object>();
            rMap.put("id",c.getId());
            rMap.put("year",c.getYear());
            rMap.put("name",c.getName());
            rMap.put("createDate", DataUtil.DateToString(c.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("creater",c.getCreater()==null?"":c.getCreater().getName());
            if(StringUtils.isNotEmpty(c.getProcessState().name())) {
                rMap.put("state", c.getProcessState().value());
//                if (state.equals("Finished")) {
//                    rMap.put("state", c.getProcessState().value());
//                } else if (state.equals("Running")) {
//                    rMap.put("state", c.getProcessState().value());
//                } else if (state.equals("Backed")) {
//                    rMap.put("state", c.getProcessState().value());
//                }
            }
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String input(){
        if(StringUtils.isNotEmpty(keyId)){
            calculationYear=calculationYearService.get(keyId);
            budgetfileId="";
            finalAccountsfileId="";
            if(calculationYear.getBudget()!=null&&calculationYear.getBudget().size()>0){
                for(FileManage c:calculationYear.getBudget()){
                    budgetfileId+=c.getId()+",";
                }
            }
            if(calculationYear.getFinalAccounts()!=null&&calculationYear.getFinalAccounts().size()>0){
                for(FileManage f:calculationYear.getFinalAccounts()){
                    finalAccountsfileId+=f.getId()+",";
                }
            }
        }
        return "input";
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            calculationYear=calculationYearService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            budgetfileId="";
            finalAccountsfileId="";
            if(calculationYear.getBudget()!=null&&calculationYear.getBudget().size()>0){
                for(FileManage b:calculationYear.getBudget()){
                    budgetfileId+=b.getId()+",";
                }
            }
            if(calculationYear.getFinalAccounts()!=null&&calculationYear.getFinalAccounts().size()>0){
                for(FileManage f:calculationYear.getFinalAccounts()){
                    finalAccountsfileId+=f.getId()+",";
                }
            }
        }
        return "read";
    }

    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                calculationYearService.update(calculationYear);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("initDuty", curDutyId);
                various.put("curDutyId", curDutyId);
                calculationYearService.save(calculationYear, "calculationyear", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            calculationYear=calculationYearService.get(keyId);
        }else{
            calculationYear=new CalculationYear();
            calculationYear.setCreater(usersService.getLoginInfo());
        }
        calculationYear.setCompany(usersService.getLoginInfo().getCompany());

        List<FileManage> budgetList= Lists.newArrayList();
        if(StringUtils.isNotEmpty(budgetIds)){
            for(String b:budgetIds.split(",")){
                budgetList.add(fileManageService.get(b.trim()));
            }
            calculationYear.setBudget(budgetList);
        }

        List<FileManage> finalAccountsList=Lists.newArrayList();
        if(StringUtils.isNotEmpty(finalAccountsIds)){
            for(String f:finalAccountsIds.split(",")){
                finalAccountsList.add(fileManageService.get(f.trim()));
            }
            calculationYear.setFinalAccounts(finalAccountsList);
        }

        String year= String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        calculationYear.setYear(year);
        calculationYear.setName(cname);
    }

    public String commit(){
        setData();
        ifCentralStaff=0;
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();

        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi" + duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        if(ifCentralStaff==1){
            var1.put("numStatus",3);
            var2.put("numStatus",3);
        }else{
            var1.put("numStatus",1);
            var2.put("numStatus",1);
        }
        var2.put("curDutyId", curDutyId);
        var2.put("ifCentralStaff", ifCentralStaff);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                calculationYearService.approve(calculationYear, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId = calculationYearService.commit(calculationYear, "calculationyear", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve1(){
        System.out.println("========app1===下属公司财务科科长===");
        ifCentralStaff=0;
        calculationYear = calculationYearService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                System.out.println("我的部门名称是：---------"+duty.getDepartment().getName());
                LogUtil.info("ceshi"+duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                calculationYearService.approve(calculationYear, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve2() {
        System.out.println("========app2===下属公司总经理===");
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        calculationYear = calculationYearService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 3);
        //  var2.put("curDutyId", curDutyId);
        try {
            calculationYearService.approve(calculationYear, FlowEnum.ProcessState.Running, var2, curDutyId,comment);

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        System.out.println("========app3===财务科科长===");
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        calculationYear = calculationYearService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        //  var2.put("curDutyId", curDutyId);
        try {
            calculationYearService.approve(calculationYear, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve4() {
        System.out.println("========app3===中心主任/中心书记\n===");
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        calculationYear = calculationYearService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 5);
        //  var2.put("curDutyId", curDutyId);
        try {
            calculationYearService.approve(calculationYear, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            calculationYear = calculationYearService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("calculationyear");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:" + numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            calculationYearService.reject(calculationYear, key, numStatus, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            calculationYear = calculationYearService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("calculationyear");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            calculationYearService.deny(calculationYear, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }

    /**
     * 失效
     * @return
     */
    public String doInvalid(){
        if(StringUtils.isNotEmpty(keyId)) {
            calculationYear = calculationYearService.get(keyId);
            calculationYear.setInvalid(true);
            calculationYearService.update(calculationYear);
        }
        return ajaxHtmlCallback("200", "操作成功！", "操作状态");
    }


    public CalculationYear getCalculationYear() {
        return calculationYear;
    }

    public void setCalculationYear(CalculationYear calculationYear) {
        this.calculationYear = calculationYear;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getBudgetfileId() {
        return budgetfileId;
    }

    public void setBudgetfileId(String budgetfileId) {
        this.budgetfileId = budgetfileId;
    }

    public String getFinalAccountsfileId() {
        return finalAccountsfileId;
    }

    public void setFinalAccountsfileId(String finalAccountsfileId) {
        this.finalAccountsfileId = finalAccountsfileId;
    }

    public String getBudgetIds() {
        return budgetIds;
    }

    public void setBudgetIds(String budgetIds) {
        this.budgetIds = budgetIds;
    }

    public String getFinalAccountsIds() {
        return finalAccountsIds;
    }

    public void setFinalAccountsIds(String finalAccountsIds) {
        this.finalAccountsIds = finalAccountsIds;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }
}
